#!/bin/sh
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/sys_check.sh"
# export GLOBAL_TOOLS_DIR="${LMD_DATA_ROOT}/scripts/global-tools"
export GLOBAL_TOOLS_DIR="${LMD_DATA_ROOT}/scripts/global-tools"
# source "$GLOBAL_TOOLS_DIR/env_node"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/env_node"

NODE_JS_DIR="${GLOBAL_TOOLS_DIR}/node"

echo "NODE_VER_DIR"$NODE_VER_DIR


convert_path() {
    local win_path="$1"

    # 1. Replace backslashes with forward slashes.
    local linux_path="${win_path//\\//}"

    # 2. Convert the drive letters in the Windows system to lowercase. C: -> /c
    if [[ $linux_path =~ ^[A-Za-z]: ]]; then
        local drive_letter=$(echo "$linux_path" | cut -c1 | tr '[:upper:]' '[:lower:]')
        local rest_path=$(echo "$linux_path" | cut -c3-)
        linux_path="/$drive_letter/$rest_path"
    fi

    # 3. clear duplicated "/".
    linux_path=$(echo "$linux_path" | sed 's|//|/|g')

    echo "$linux_path"
}

if [ -f /etc/os-release ]; then
    echo "Linux system."
    echo "Not yet support."
elif [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
    echo "macOS system."
    ARCH=$(uname -m)
    
    if [ "$ARCH" == "x86_64" ]; then
        NODE_VER_DIR=node-v${_NODE_VERSION}-darwin-x64
    elif [ "$ARCH" == "arm64" ]; then
        NODE_VER_DIR=node-v${_NODE_VERSION}-darwin-arm64
    fi
    NODE_BINARY_DIR="$NODE_JS_DIR/$NODE_VER_DIR/bin"

    alias npm="$NODE_BINARY_DIR/npm"
    alias node="$NODE_BINARY_DIR/node"
    alias npx="$NODE_BINARY_DIR/npx"
elif current_os_is_windows; then
    echo "Windows system."
    NODE_VER_DIR=node-v${_NODE_VERSION}-win-x64
    NODE_BINARY_DIR="$NODE_JS_DIR/$NODE_VER_DIR"

    alias npm=$(convert_path "$NODE_BINARY_DIR/npm")
    alias node=$(convert_path "$NODE_BINARY_DIR/node")
    alias npx=$(convert_path "$NODE_BINARY_DIR/npx")
else
    echo "Unknown OS"
fi


# add node dir to PATH
# export PATH=$PATH:"${NODE_BINARY_DIR}/"
export PATH="${NODE_BINARY_DIR}/":$PATH

